<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\model\post;

class ThePost extends Controller
{
    //
    public function __construct(){
    	date_default_timezone_set("Asia/Shanghai");
    }

    public function getThePost(Request $request){
    	$post = $request->json()->all();
    	$id = isset($post['id']) ? $post['id'] : 0;
    	$page = $post['page'];
    	$mode = $post['mode'];
    	$inpage = env('APP_PAGENUM', 10);
		$allpage = ceil(DB::table('sots_post')->count() / $inpage);
    	if ($mode == 'title') {
			if ($page > $allpage) {
				return ['code' => 201, 'data' => 'false'];
			}
			$data = DB::table('sots_post')->select()->where([['status', 'processed']])->orderBy('commit_time', 'desc')->skip(($page - 1) * $inpage)->take($inpage)->get()->toArray();
			return $data;
    	}else{
    		$thePost = $this->thePost($id);
    		$thePost = json_decode(json_encode($thePost), true);
    		return $thePost;
    	}
    	
    }

    private function thePost($doc){
        $thePost = new post($doc);
        $result['post'] = $thePost->getPost();
        $result['append'] = $thePost->getPostAppend();
        return $result;
    }

    public function addPost(Request $request){
    	$post = $request->all();

    	$new = new post();
    	$success = $new->newPost($post) ? 1 : 0;
    	if ($success != 1) {
    		$error['code'] = 3;
    		$error['success'] = 0;
    		return $error;
    	}
    	return $success;
    }

    public function appendThePost(Request $request){
    	$append = $request->all();

    	$post = new post($append['doc']);
    	unset($append['doc']);

    	$success = $post->appendThePost($append) ? 1 : 0;

    	if ($success != 1) {
    		$error['code'] = 3;
    		$error['success'] = 0;
    		return $error;
    	}
    	return $success;
    }
}
